package com.wn.test;

import com.wn.bean.Student;
import org.apache.commons.beanutils.BeanUtils;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.Test;

import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author yellow Docter
 * @date 2022 -07-07
 * @desc
 */
public class SpringTest4 {

    @Test
    public void demo01() throws DocumentException, ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException {

        Map<String,Object> application = new HashMap<>();

        /**
         * / 读取的是 src下面的 文件
         *   读取的是 src下面的  包下面的文件
         *
         *
         * 手动解析 xml 的applicationContext.xml 文件创建一个对象
         *
         * 01 添加依赖
         *
         * 02 读取 application.xml 文件流
         */
        // 拿到解析器
        SAXReader saxReader = new SAXReader();

        InputStream is = SpringTest4.class.getResourceAsStream("/applicationContext.xml");

        // 拿到文档对象
        Document document = saxReader.read(is);

        Element rootElement = document.getRootElement();
        // 拿到 根元素
        System.out.println(rootElement.getName());

        // 从 beans 拿到 所有的 bean标签
        List<Element> beans = rootElement.elements("bean");
        Element beanEle = beans.get(0);

        System.out.println(beanEle.getName());

        String id = beanEle.attribute("id").getValue();
        String clazzPath = beanEle.attribute("class").getValue();

        // bean标签下面 解析 property 标签
        List<Element> propertyEle = beanEle.elements("property");
        System.out.println("&&&&&&&&&&propertyEle 标签的名称 &&&&&&&&&&&&");

        Map<String,Object> map = new HashMap<>();

        for (Element element : propertyEle) {

            //拿到 name里面的属性值
            Attribute attr = element.attribute("name");
            String name = attr.getValue();

            //拿到 name里面的value值
            Attribute attr2 = element.attribute("value");
            String value = attr2.getValue();
            System.out.println("name = " + name);
            System.out.println("value = " + value);
            map.put(name,value);

        }

        // 解析创建了对象 丢入ioc容器中
        System.out.println("id = " + id);
        System.out.println("clazzPath = " + clazzPath);

        Class<Student> clazz = (Class<Student>) Class.forName(clazzPath);
        Student student = clazz.newInstance();

        //使用spring的uitls进行 把map转成 Bean
        BeanUtils.populate(student,map);

        System.out.println("student = " + student);
        application.put(id,student);


        // 从 ioc容器中获取对象
        Student stu = (Student) application.get("stu");
        System.out.println("stu = " + stu);

    }

}
